/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.h2t.loveplace.views.components;

import com.h2t.loveplace.data.LocationTest;
import com.h2t.loveplace.data.PointPlace;
import com.h2t.loveplace.location.GpsLocationFinder;
import com.h2t.loveplace.main.LoveplaceMidlet;
import com.h2t.loveplace.models.Place;
import com.h2t.loveplace.views.canvas.MapCanvas;
import com.nokia.maps.common.ApplicationContext;
import com.nokia.maps.common.GeoCoordinate;
import com.nokia.maps.common.Location;
import com.nokia.maps.map.MapComponent;
import com.nokia.maps.map.MapDisplay;
import com.nokia.maps.map.MapFactory;
import com.nokia.maps.map.MapListener;
import com.nokia.maps.map.MapMarker;
import com.nokia.maps.map.MapStandardMarker;
import com.nokia.maps.map.Point;
import com.nokia.maps.routing.Route;
import com.nokia.maps.routing.RouteFactory;
import com.nokia.maps.routing.RouteListener;
import com.nokia.maps.routing.RouteManeuver;
import com.nokia.maps.routing.RouteRequest;
import com.nokia.maps.routing.RoutingMode;
import com.nokia.maps.routing.RoutingType;
import com.nokia.maps.routing.TransportMode;
import com.nokia.maps.routing.WaypointParameterList;
import com.nokia.maps.search.GeocodeRequest;
import com.nokia.maps.search.GeocodeRequestListener;
import com.nokia.maps.search.SearchFactory;
import com.sun.lwuit.Button;
import com.sun.lwuit.Component;
import com.sun.lwuit.Form;
import com.sun.lwuit.Graphics;
import com.sun.lwuit.Label;

import java.util.Hashtable;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Image;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import javax.microedition.location.QualifiedCoordinates;

/**
 *
 * @author PHAN THAI
 */
public class Map extends Component implements MapListener, RouteListener {

    private static MapCanvas mapCanvas;
    private static MapDisplay mapDisplay;
    private static MapFactory factory;
    private final String APP_ID = "6FD2N8mr7xYOympkU1x8";
    private final String TOKEN_ID = "NN-cLK80AD-410S0Q8EkBA";
    private Display display;
    private int markerCount;
    private Hashtable markerDataTable;
    private Image helperImg;
    private javax.microedition.lcdui.Graphics helperImgGraphics;
    
    RouteManeuver currentManeuver = null;
    MapStandardMarker currentMarker = null;
    
    private Place place;
  

    public Map(Display display, Place place) {
        this.display = display;
        this.place = place;

  //      setWidth(100);
 //       setHeight(100);
        createMap();
      //  getStyle().setBgColor(0x3333);
//        addComponent(new Button("..."));
    }

    private void createMap() {
        ApplicationContext.getInstance().setAppID(APP_ID);
        ApplicationContext.getInstance().setToken(TOKEN_ID);
        mapCanvas = new MapCanvas(display);
        factory = mapCanvas.getMapFactory();
        mapDisplay = mapCanvas.getMapDisplay();
        mapDisplay.setMapListener(this);
//        if(place == null) {
//            mapDisplay.setCenter(new GeoCoordinate(LocationTest.current.getLat(), LocationTest.current.getLon(), 0));   // Defaul Buu dien Hanoi
//        }
//        else {
//            mapDisplay.setCenter(new GeoCoordinate(place.getLat(), place.getLon(), 0));  
//        }
        mapDisplay.setZoomLevel(15, 0, 0);
        setFocusable(true);
        markerCount = 0;
        markerDataTable = new Hashtable();
        
        
    }
    
    private void createRoute(double lat, double lon) {
        WaypointParameterList waypoints = new WaypointParameterList();
        waypoints.addCoordinate(new GeoCoordinate(lat, lon, 0.0f));
        waypoints.addCoordinate(new GeoCoordinate(LocationTest.current.getLat(), LocationTest.current.getLon(), 0.0f));

        RoutingMode[] routingModes = new RoutingMode[1];
        routingModes[0] = new RoutingMode(
                RoutingType.FASTEST,
                new int[]{TransportMode.CAR},
                new String[0]);

        RouteFactory rf = RouteFactory.getInstance();

        rf.createRouteRequest().calculateRoute(waypoints, routingModes, this);
        repaint();
    }
    
    public void setPlace(Place place) {
        this.place = place;
       // mapDisplay.setCenter(new GeoCoordinate(lat, lon, 0));
        createRoute(place.getLat(), place.getLon());
        repaint();
    }
    
    public Place getPlace() {
        return place;
    }

    public void paint(Graphics g) {
        super.paint(g);
        g.drawLine(6, 5, 100, 100);
        if (helperImg == null) {
            helperImg = javax.microedition.lcdui.Image.createImage(getWidth(), getHeight());
            helperImgGraphics = helperImg.getGraphics();
        }
        mapDisplay.paint(helperImgGraphics);
        MapComponent[] comps = mapDisplay.getAllMapComponents();
        for (int i = 0; i < comps.length; i++) {
            comps[i].paint(helperImgGraphics);
        }
        com.sun.lwuit.Image img = com.sun.lwuit.Image.createImage(helperImg);
        g.drawImage(img, 0, 0);
    }

    public void onMapContentComplete() {
        repaint();
    }

    public void onMapContentUpdated() {
        repaint();
    }

    public void onMapUpdateError(String string, Throwable thrwbl, boolean bln) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public MapDisplay getMapDisplay() {
        return mapDisplay;
    }

    public void addMarker(GeoCoordinate coord, Image img, Object data) {
        // my code
        if (img != null) {
            MapMarker marker = factory.createMapMarker(coord, img);
            marker.setAnchor(new Point(-img.getWidth() / 2, -img.getHeight() / 2));
            mapDisplay.addMapObject(marker);
            markerDataTable.put(marker, data);
        } else {
            MapStandardMarker marker = factory.createStandardMarker(coord);
            mapDisplay.addMapObject(marker);
            markerDataTable.put(marker, data);
        }
        if (++markerCount == 1) {
            mapDisplay.setCenter(coord);
        }
    }

    public void onRequestComplete(RouteRequest rr, Route[] routes) {
        if (routes.length > 0) {
            Route firstRoute = routes[0];
         //   ;
            mapDisplay.addMapObject(factory.createMapPolyline(firstRoute.getShape(), 3));
            setCurrentManeuver(firstRoute.getFirstManeuver());
        } else {
            System.out.println("Router not found");
        }
     //   repaint();
    }

    public void onRequestError(RouteRequest rr, Throwable thrwbl) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    private synchronized void setCurrentManeuver(RouteManeuver maneuver) {
        if (currentMarker == null) {
             currentMarker = factory.createStandardMarker(maneuver.getPosition());
             mapDisplay.addMapObject(currentMarker);
        } else {
            currentMarker.setCoordinate(maneuver.getPosition());
            //repaint();
        }

        currentManeuver = maneuver;
        mapDisplay.setCenter(currentManeuver.getPosition());

       // repaint();
    }

}
